<?php

namespace App\Services;

use App\Models\Post;
use App\Models\Reply;
use App\Models\Report;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class AdminService
{
    /**
     * 处理举报
     *
     * @param  User  $admin  管理员
     * @param  array  $data  处理数据
     */
    public function processReport(Report $report, User $admin, array $data): Report
    {
        if (! $admin->isAdmin()) {
            throw new \Illuminate\Auth\Access\AuthorizationException('您无权处理此举报');
        }

        return DB::transaction(function () use ($report, $admin, $data) {
            $report->update([
                'status' => $data['status'], // resolved 或 rejected
                'admin_id' => $admin->id,
                'admin_comment' => $data['admin_comment'] ?? null,
                'processed_at' => now(),
            ]);

            // 如果举报被处理为 resolved，根据举报原因执行相应操作
            if ($data['status'] === 'resolved' && isset($data['action'])) {
                $this->executeAction($report, $data['action']);
            }

            return $report->fresh();
        });
    }

    /**
     * 执行处理操作
     *
     * @param  string  $action  操作：delete（删除）、warn（警告）、no_action（不处理）
     */
    protected function executeAction(Report $report, string $action): void
    {
        $reportable = $report->reportable;

        switch ($action) {
            case 'delete':
                if ($reportable instanceof Post) {
                    $reportable->delete();
                } elseif ($reportable instanceof Reply) {
                    $reportable->delete();
                }
                break;
            case 'warn':
                // TODO: 实现警告功能（可以记录到用户表中）
                break;
            case 'no_action':
                // 不执行任何操作
                break;
        }
    }

    /**
     * 获取待处理举报数
     */
    public function getPendingReportsCount(): int
    {
        return Report::where('status', 'pending')->count();
    }
}
